import { Directive, ElementRef, Input } from '@angular/core';
import { PermitConfigMode, ZeprideAuthorityData } from '../engines/models';
import { AuthorityService } from './authority.service';

@Directive({
  selector: '[zeprideAuthority]'
})
export class AuthorityDirective {

  constructor(
    private el: ElementRef<HTMLElement>,
    private authorityService: AuthorityService
  ) { }

  @Input() set zeprideAuthority(auth: ZeprideAuthorityData) {
    if (!auth || !auth.refObjectId || !auth.permitConfigs || !this.authorityService.turnOn) {
      return;
    }
    for (const permit of auth.permitConfigs) {
      const permitId = permit.permitId;
      const mode = permit.mode;
      const isAuthorized = this.authorityService.checkAuthority({ refObjectId: auth.refObjectId, permitId, mode });
      if (!isAuthorized) {
        this.setElementStyleByMode(mode);
      }
      if (auth.afterChecked) {
        setTimeout(() => {
          auth.afterChecked({ permitId, isAuthorized });
        }, 0);
      }
    }
  }

  private setElementStyleByMode(mode: PermitConfigMode) {
    switch (mode) {
      case 'edit':
        this.el.nativeElement.classList.add('zepride-unauthorized');
        this.el.nativeElement.title = '没有权限';
        // this.el.nativeElement.setAttribute('disabled', 'disabled');
        // this.el.nativeElement.setAttribute('readonly', 'readonly');
        this.el.nativeElement.setAttribute('unauthorized', mode);
        break;
      case 'query':
        this.el.nativeElement.classList.add('zepride-unauthorized');
        this.el.nativeElement.title = '没有权限';
        // this.el.nativeElement.setAttribute('disabled', 'disabled');
        // this.el.nativeElement.setAttribute('readonly', 'readonly');
        this.el.nativeElement.setAttribute('unauthorized', mode);
        break;
    }
  }
}
